package com.qiche.controller.mgr;

import com.github.pagehelper.PageInfo;
import com.qiche.aspect.PageResult;
import com.qiche.aspect.Result;
import com.qiche.dto.InsurancePolicyDto;
import com.qiche.dto.ProductDto;
import com.qiche.dto.SimpleInsurancePolicyItemDto;
import com.qiche.enums.ResultEnum;
import com.qiche.exception.MySystemException;
import com.qiche.model.*;
import com.qiche.requestpram.PolicyListURL;
import com.qiche.service.*;
import com.qiche.util.DateTimeUtils;
import com.qiche.util.UserUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 保单管理控制器
 * Created by Linzw on 2018/01/24.
 */
@Api(value = "/policys",description = "保单管理控制器")
@RestController
@RequestMapping("/policys")
public class InsurancePolicyController {
    @Resource
    private InsurancePolicyService policyService;

    @Resource
    private CardLinkService cardLinkService;
    @Resource
    private MerchantService merchantService;
    @Resource
    private ProductService productService;
    @Resource
    private GiftPackageService giftPackageService;
    @Resource
    private StoreMemberService storeMemberService;



    @ApiOperation(value ="根据条件和分页获取保单列表" )
    @GetMapping
    public Map<String, Object> getAll(InsurancePolicy policy,
                                      @RequestParam(required = false, defaultValue = "1") int page,
                                      @RequestParam(required = false, defaultValue = "10") int limit) {
        Map<String, Object> map = new HashMap<>();
        PageInfo<InsurancePolicy> pageInfo = policyService.selectByPage(policy, page, limit);

        List<InsurancePolicyDto> dtos=new ArrayList<>();
        for (InsurancePolicy tempPolicy:pageInfo.getList()) {
            InsurancePolicyDto dto=new InsurancePolicyDto();
            tempPolicy.setStatus((byte) DateTimeUtils.isExpriedByPolicy(tempPolicy.getExpiryTime(),90));
            BeanUtils.copyProperties(tempPolicy,dto);
            Merchant merchant=merchantService.selectById(tempPolicy.getMerchantId());
            if(merchant!=null){
                dto.setBelongMerchantName(merchant.getName());
            }
            dtos.add(dto);
        }
        map.put("code", 0);
        map.put("msg", "查询成功");
        map.put("count", pageInfo.getTotal());
        map.put("data", dtos);
        return map;
    }


    @ApiOperation(value = "添加保单")
    @PostMapping
    public Result add(@RequestBody @Validated InsurancePolicy policy, BindingResult result) {

        if (result.hasErrors()) {
            return Result.createByResultEnum(ResultEnum.PARAM_ERROR);
        }
        User currentUser =UserUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }
        try {
            return policyService.savePolicy(policy, currentUser);
        } catch (MySystemException e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.POLICY_HAS_EXISTED);
        } catch (Exception e) {
            return Result.createByResultEnum(ResultEnum.FAILURE);
        }
    }

    @ApiOperation(value ="更新保单" )
    @PutMapping
    public Result update(@RequestBody InsurancePolicy policy) {
        User currentUser =UserUtils.getCurrentUser();
        if (currentUser == null) {
            return Result.createByResultEnum(ResultEnum.MEMBER_LOGIN_PAST);
        }
        try {
            return policyService.updatePolicy(policy, currentUser);
        } catch (MySystemException e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.POLICY_HAS_EXISTED);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.createByResultEnum(ResultEnum.FAILURE);
        }
    }

    @ApiOperation(value = "根据保单ID 和会员ID查出礼包中的产品列表")
    @GetMapping(value = "/getByPidWithLinks/{policyId}/{memberId}")
    public Map<String, Object> getByPidWithLinks(@PathVariable("policyId") Long policyId,
                                                 @PathVariable("memberId") Long memberId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        // 需要返回的信息 1.保单 2：产品列表
        StoreMember member = storeMemberService.selectByKey(memberId);
        InsurancePolicy policy = null;
        List<CardLink> links = null;
        if (policyId == 0) {
            // 这种是无保单的,根据memberId联合去查
            policy = null;
            links = cardLinkService.selectByMemberAndPolicy(memberId, policyId);
        } else {
            policy = policyService.selectById(policyId);
            links = cardLinkService.selectByPolicyId(policy.getId());
        }
        List<Long> ownerWelfares = new ArrayList<>();
        List<ProductDto> productDtos = new ArrayList<>();
        int initPrice = 0;
        for (CardLink cardLink : links) {
            if (cardLink.getProductId() != 0) {
                Product temp = productService.selectById(cardLink.getProductId());
                ProductDto productDto = new ProductDto();
                BeanUtils.copyProperties(productDto, temp);
                productDto.setCount(cardLink.getCount());
                productDtos.add(productDto);
                productDto.setUsePeriod(cardLink.getUsePeriod());
            } else {
                if (cardLink.getWelfareId() != null && cardLink.getWelfareId() != 0) {
                    ownerWelfares.add(cardLink.getWelfareId());
                }
            }

        }
        GiftPackage pack = giftPackageService.selectByMemberAndPolicy(memberId, policyId);
        map.put("code", 200);
        map.put("productDtos", productDtos);
        map.put("ownerWelfares", ownerWelfares);
        map.put("policy", policy);
        map.put("member", member);
        map.put("initPrice", initPrice);
        map.put("pack", pack);
        return map;
    }


    @ApiOperation(value = "根据ID获取保单信息")
    @GetMapping(value = "/getById/{id}")
    public Result<InsurancePolicy> getById(@PathVariable("id") Long id) {
        InsurancePolicy policy = policyService.selectById(id);
        return  Result.createBySuccess(policy);
    }

    @ApiOperation(value = "根据ID删除保单信息")
    @DeleteMapping(value = "/delete/{id}")
    public Result<String> delete(@PathVariable("id") Long id) {
        return  policyService.delInsurancePolicy(id);
    }


    @ApiOperation(value = "根据客户ID获取保单列表")
    @GetMapping(value = "/getListByCustomerId/{customerId}")
    public Result<List<InsurancePolicy>> getListByCustomerId(@PathVariable("customerId") Long customerId){
        List<InsurancePolicy> insurancePolicies=policyService.selectByCustomerId(customerId);
        return Result.createBySuccess(insurancePolicies);
    }




}
